package com.sfzd5.UI;

import com.sfzd5.whiteboard.WhiteBoard;
import org.cef.CefApp;
import org.cef.CefClient;
import org.cef.OS;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.handler.CefLifeSpanHandlerAdapter;
import org.cef.handler.CefLoadHandler;
import org.cef.network.CefRequest;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;

public class QuestionInfoDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonCancel;
    private JComboBox cb_widthMode;
    private JButton 增大Button;
    private JButton 减小Button;
    private JButton 标注Button;
    private JLabel lb_msg;
    private JPanel webViewPanel;
    private JLabel lb_rightRate;
    private JPanel mPanel;
    private JButton 放大Button;
    private JButton 缩小Button;

    String html;
    float rightRate;
    int fontSize = 30;
    int imgzoom = 30;

    WhiteBoard whiteBoard;
    CardLayout card;

    String curCardNmae;

    private CefApp cefApp_;
    private CefClient client_;
    private CefBrowser browser_;
    private Component browerUI_;

    private void initCEF(String startURL) {
        boolean useOSR = OS.isLinux();
        cefApp_ = CefApp.getInstance();
        client_ = cefApp_.createClient();

        browser_ = client_.createBrowser(startURL, useOSR, false);
        browerUI_ = browser_.getUIComponent();

        client_.addLifeSpanHandler(new CefLifeSpanHandlerAdapter() {
            @Override
            public boolean onBeforePopup(CefBrowser browser, CefFrame frame, String target_url, String target_frame_name) {
                browser.loadURL(target_url);
                return true;
            }
        });

        client_.addLoadHandler(new CefLoadHandler() {
            @Override
            public void onLoadingStateChange(CefBrowser cefBrowser, boolean b, boolean b1, boolean b2) {

            }

            @Override
            public void onLoadStart(CefBrowser cefBrowser, CefFrame cefFrame, CefRequest.TransitionType transitionType) {

            }

            @Override
            public void onLoadEnd(CefBrowser cefBrowser, CefFrame cefFrame, int i) {
                resetWebView();
                client_.removeLoadHandler();
            }

            @Override
            public void onLoadError(CefBrowser cefBrowser, CefFrame cefFrame, ErrorCode errorCode, String s, String s1) {

            }
        });

        webViewPanel.add("webview", browerUI_);
        resetWebView();
    }


    public QuestionInfoDialog(String html, float rightRate) {
        setContentPane(contentPane);
        setModal(true);

        this.html = html;
        this.rightRate = rightRate;

        lb_rightRate.setText(String.valueOf(rightRate) + "%");

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        增大Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fontSize += 5;
                resetWebView();
                lb_msg.setText("字体" + fontSize);
            }
        });
        减小Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fontSize -= 5;
                resetWebView();
                lb_msg.setText("字体" + fontSize);
            }
        });
        标注Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (curCardNmae.equals("webview")) {
                    /*
                    Dimension size = browerUI_.getSize(); //.getPreferredSize();
                    BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); //截取大小
                    Graphics2D g2 = image.createGraphics();
                    browerUI_.paintAll(g2);
                    */

                    java.awt.Component component =browerUI_;
                    java.awt.Point p = new java.awt.Point(0, 0);
                    javax.swing.SwingUtilities.convertPointToScreen(p, component);
                    java.awt.Rectangle region = component.getBounds();
                    region.x = p.x;
                    region.y = p.y;

                    BufferedImage image = null;
                    try {
                        image = new Robot().createScreenCapture(region);
                    } catch (AWTException awtException) {
                        awtException.printStackTrace();
                    }


                    whiteBoard.setBackgroundImage(image);
                    whiteBoard.clear();

                    标注Button.setText("关闭标注");
                    增大Button.setEnabled(false);
                    减小Button.setEnabled(false);
                    cb_widthMode.setEnabled(false);
                    curCardNmae = "whiteBoard";
                    card.show(webViewPanel, curCardNmae);
                    lb_msg.setText("标注讲解");
                } else {
                    标注Button.setText("标注");
                    增大Button.setEnabled(true);
                    减小Button.setEnabled(true);
                    cb_widthMode.setEnabled(true);
                    curCardNmae = "webview";
                    card.show(webViewPanel, curCardNmae);
                    lb_msg.setText("习题浏览");
                }
            }
        });

        cb_widthMode.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    resetWebView();
                    String width = (String) cb_widthMode.getSelectedItem();
                    lb_msg.setText("宽度模式：" + width);
                }
            }
        });

        card = (CardLayout) webViewPanel.getLayout();
        whiteBoard = new WhiteBoard();
        webViewPanel.add("whiteBoard", whiteBoard.mPanel);
        initCEF("about:blank");
        curCardNmae = "webview";
        card.show(webViewPanel, curCardNmae);


        缩小Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                imgzoom -= 5;
                resetWebView();
            }
        });
        放大Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                imgzoom += 5;
                resetWebView();
            }
        });
    }


    private void onCancel() {
        // add your code here if necessary
        dispose();
    }


    private void resetWebView() {
        browser_.loadString(generateQuestionHtml(), "https://zujuan.21cnjy.com/");
    }

    public String generateQuestionHtml() {
        String width = (String) cb_widthMode.getSelectedItem();
        if (width.equals("窗口")) {
            width = "100%";
        } else {
            width += "px";
        }
        String fontSzie = this.fontSize + "px";
        StringBuilder sb = new StringBuilder();
        sb.append("<!DOCTYPE html><html><head><meta charset=\"utf-8\" /><style type=\"text/css\"> img{ width:"+imgzoom+"%; height: auto; } .question{ margin:0 auto; width:")
                .append(width)
                .append("; font-size:")
                .append(fontSzie)
                .append("; text-align:left; } </style> </head> <body> <div class=\"question\">")
                .append(html)
                .append("</div></body></html>");
        return sb.toString();
    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        contentPane = new JPanel();
        contentPane.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 1, new Insets(10, 10, 10, 10), -1, -1));
        final JPanel panel1 = new JPanel();
        panel1.setLayout(new BorderLayout(0, 0));
        contentPane.add(panel1, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        mPanel = new JPanel();
        mPanel.setLayout(new BorderLayout(0, 0));
        mPanel.setPreferredSize(new Dimension(1000, 600));
        panel1.add(mPanel, BorderLayout.CENTER);
        final JToolBar toolBar1 = new JToolBar();
        toolBar1.setBorderPainted(false);
        toolBar1.setFloatable(false);
        mPanel.add(toolBar1, BorderLayout.NORTH);
        cb_widthMode = new JComboBox();
        cb_widthMode.setMaximumSize(new Dimension(78, 32767));
        final DefaultComboBoxModel defaultComboBoxModel1 = new DefaultComboBoxModel();
        defaultComboBoxModel1.addElement("窗口");
        defaultComboBoxModel1.addElement("600");
        defaultComboBoxModel1.addElement("800");
        defaultComboBoxModel1.addElement("1000");
        cb_widthMode.setModel(defaultComboBoxModel1);
        toolBar1.add(cb_widthMode);
        增大Button = new JButton();
        增大Button.setText("增大");
        toolBar1.add(增大Button);
        减小Button = new JButton();
        减小Button.setText("减小");
        toolBar1.add(减小Button);
        标注Button = new JButton();
        标注Button.setText("标注");
        toolBar1.add(标注Button);
        buttonCancel = new JButton();
        buttonCancel.setText("关闭");
        toolBar1.add(buttonCancel);
        final JLabel label1 = new JLabel();
        label1.setText("正确率：");
        toolBar1.add(label1);
        lb_rightRate = new JLabel();
        lb_rightRate.setText("10%");
        toolBar1.add(lb_rightRate);
        final JToolBar toolBar2 = new JToolBar();
        toolBar2.setBorderPainted(false);
        toolBar2.setFloatable(false);
        mPanel.add(toolBar2, BorderLayout.SOUTH);
        lb_msg = new JLabel();
        lb_msg.setText("信息");
        toolBar2.add(lb_msg);
        webViewPanel = new JPanel();
        webViewPanel.setLayout(new CardLayout(0, 0));
        mPanel.add(webViewPanel, BorderLayout.CENTER);

    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return contentPane;
    }
}
